

var fs = require('fs');

var myArgs = process.argv.slice(1);

var keywords = ["BEGIN","VERSION","BEGIN", "DTSTART", "DURATION", "ATTENDEE", "LOCATION", "END"];

var rendezVousData = new Array();

var input= new Array();

//Fonction principale. Lit un fichier ics et retourne les infos nécessaires à l'objet RendezVous sous forme de tableau.
//Ordre DTSTAMP, DTSTART, DURATION, ATTENDEE, LOCATION
function fromICal(){

fs.readFile(myArgs[1], 'utf8', function (err,data) {
  
	if (err) {
		return console.log(err);
	}
	
	data = unfold(data);
	input = data.split("\n");
	for(var i=0 ; i<input.length; i++){
		input[i] = input[i].split(":");
	}
	
	calendar();
	
	return rendezVousData;
	
});
}

//Parse un VCALENDAR
function calendar(){
		expectDefinedData("BEGIN","VCALENDAR");
		expectDefinedData("VERSION","2.0")
		expectEvent();
		expectDefinedData("END","VCALENDAR")
}

//Parse un VEVENT
function expectEvent(){

	expectDefinedData("BEGIN","VEVENT");
	expect("DTSTAMP");
	expect("DTSTART");
	expect("DURATION");
	expect("ATTENDEE");
	expect("LOCATION");
	expectDefinedData("END","VEVENT");

}

function expect(s){

	var currentLine = next();
	if(currentLine[0] == s){
	console.log("Trouve : " +s);
		rendezVousData.push(currentLine[1]);
		return true;
	}
	else{
		error(currentLine[0]);
		return false;
	}
}

//S'intéresse aux éléments fixes.
//SKey correspond à la partie gauche des ":", SValue à la partie droite
function expectDefinedData(SKey, SValue){

	var currentLine = next();
		
	if(currentLine[0] == SKey && currentLine[1] == SValue){
		console.log("Trouve : " + SKey);
		return true;
	}
	else{
		error(currentLine[0]);
		return false;
	}
}

function error(pos){
console.log("Symbole inattendu : "+ pos);
	process.exit(0);
}


function next(){
	if(input.length > 1){
		return input.shift();
	}
	else{
		return input[0];
	}
}
	
	
//Reconstruit les lignes éclatées
function unfold(icalString){

for(var i = 0; i<icalString.length; i++){

	if(icalString.charAt(i) == "\n"){
		if(icalString.charAt(i+1) == " " || icalString.charAt(i+1) == "\t"){
			icalString = icalString.slice(0, i) + icalString.slice(i+2);
		}
	}
}
return icalString;
}	


